<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
// import type { XtxGuessInstance } from '@/types/components'
import PageSkeletion from './components/PageSkeleton.vue'

import { useGuessList } from '@/composables/index'

const bannerList = ref<BannerItem[]>([])
const categoryList = ref<CategoryItem[]>([])
const hotList = ref<HotItem[]>([])
// const guessRef = ref<XtxGuessInstance>()

const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
  // console.log(res)
}
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}
const getHomeHotPanelData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

const { guessRef, onScrolltolower } = useGuessList()

// const onScrolltolower = () => {
//   guessRef.value?.getMore()
// }
const isTriggered = ref<boolean>(false)
// 自定义下拉刷新触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 加载数据  串联的发送
  // await getHomeBannerData()
  // await getHomeCategoryData()
  // await getHomeHotPanelData()
  // 并行发送  提升效率 性能
  // 重置猜你喜欢数据

  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotPanelData(),
    guessRef.value?.resetData(),
  ])
  // 关闭动画
  isTriggered.value = false
}
// 是否加载
const isLoading = ref<boolean>(false)

onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotPanelData()])
  isLoading.value = false
})
</script>

<template>
  <CustomNavbar />
  <scroll-view
    class="scroll-view"
    scroll-y
    @scrolltolower="onScrolltolower"
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
  >
    <!-- 滚动容器 -->
    <PageSkeletion v-if="isLoading" />
    <template v-else>
      <XtxSwiper :list="bannerList" />
      <CategoryPanel :list="categoryList" />
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
  // 占满剩余的高度
}
</style>
